package com.example.generator;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;

import java.io.File;
import java.util.Collections;

@Slf4j
public class MybatisPlusGenerator {

    public static void generator(String url, String username, String password, String parent, String[] tables, String[] tablePrefix) {
        File webRoot = FileUtil.getWebRoot().getAbsoluteFile();
        String author = "developer";
        String commentDatePattern = "yyyy-MM-dd";
        String mybatis = webRoot.getAbsolutePath() + "/mybatis";
        String mapper = webRoot.getAbsolutePath() + "/mybatis/mapper";

        FileUtil.del(mybatis);
        FileUtil.del(mapper);
        FastAutoGenerator.create(url, username, password).globalConfig(builder -> builder.author(author).disableOpenDir().outputDir(mybatis).commentDate(commentDatePattern)).packageConfig(builder -> builder.parent(parent).pathInfo(Collections.singletonMap(OutputFile.xml, mapper))).strategyConfig(builder -> builder.addInclude(tables).addTablePrefix(tablePrefix).controllerBuilder().enableHyphenStyle().enableRestStyle().serviceBuilder().mapperBuilder().enableBaseResultMap().mapperAnnotation(Mapper.class).entityBuilder().disableSerialVersionUID().enableTableFieldAnnotation().enableLombok()).templateEngine(new FreemarkerTemplateEngine()).execute();

        replaceMoreThanOneTableId(mybatis + "/" + parent.replace(".", "/") + "/entity");
        log.info("输出目录：{}", mybatis);
    }

    /**
     * mybatis-plus不支持多主键，替换多主键TableId为TableField
     */
    private static void replaceMoreThanOneTableId(String path) {
        File[] files = FileUtil.ls(path);
        if (files == null) {
            return;
        }
        for (File file : files) {
            String string = FileUtil.readUtf8String(file.getAbsoluteFile());
            // 增加``，防止关键词冲突
            String replace = string.replace("(\"", "(\"`").replace("\")", "`\")");
            // 替换多余的TableId为TableField
            replace = StrUtil.replace(replace, string.indexOf("@TableId") + 8, "@TableId", "@TableField", false);
            // 替换update_time为字段更新策略never不加入sql
            if (replace.contains("@TableField(\"`update_time`\")")) {
                String dl = System.lineSeparator() + System.lineSeparator();
                replace = StrUtil.replaceFirst(replace, dl, dl + "import com.baomidou.mybatisplus.annotation.FieldStrategy;\r\n", false);
                replace = StrUtil.replace(replace, "@TableField(\"`update_time`\")", "@TableField(value = \"`update_time`\", updateStrategy = FieldStrategy.NEVER)");
            }
            FileUtil.writeUtf8String(replace, file.getAbsolutePath());
        }
    }
}